package run.iget.framework.common.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import run.iget.framework.common.resp.ResultResp;

import java.util.List;
import java.util.Objects;


/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * 将RestController方法的返回值都包装成统一的格式
 * ---------------类描述-----------------
 *
 * @author 大周
 * @date 2022/11/11 21:47
 */
@Slf4j
@RestControllerAdvice
public class RestControllerAdviceHandler implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        if (body instanceof ResultResp) {
            return body;
        }
        if (this.notNeedConvertResultResp(request)) {
            return body;
        }
        serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        ResultResp responseEntity = ResultResp.ok(body);
        // 如果是String类型，需要返回string对象
        if (body instanceof String) {
            return JSON.toJSONString(responseEntity);
        }
        return responseEntity;
    }

    /**
     * 是否需要转换为包装对象
     *
     * @param request 请求对象
     * @return contentType或accept中包含json，则进行返回true
     */
    private boolean notNeedConvertResultResp(ServerHttpRequest request) {
        MediaType contentType = request.getHeaders().getContentType();
        List<MediaType> accept = request.getHeaders().getAccept();
        if (!isContainsJson(contentType) && !isContainsJson(accept)) {
            return true;
        }
        return false;
    }

    private boolean isContainsJson(MediaType contentType) {
        if (Objects.isNull(contentType) || StrUtil.isBlank(contentType.getSubtype())) {
            return false;
        }
        return StrUtil.containsIgnoreCase(contentType.getSubtype(), "json");
    }

    private boolean isContainsJson(List<MediaType> accept) {
        if (CollectionUtil.isEmpty(accept)) {
            return false;
        }
        return accept.stream().anyMatch(this::isContainsJson);
    }
}
